const express = require('express');
const router = express.Router();
const orderMod = require('../db/orderMod');
const userMod = require('../db/userMod');
const balanceRecordMod = require('../db/balanceRecordMod');
const { localDate, adminName } = require('../serverOpt');
const debug = require('debug')('a-sokio-yun:server');

// 获取订单列表
router.get('/list', async function (req, res) {
	const { userName, userId } = req.session;
	if (!userName || !userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}

	try {
		const query = req.query;
		let searchCondition = { isDeleted: false };

		// 非管理员只能看自己的订单
		if (userName !== adminName) {
			searchCondition.createUser = userId;
		}

		// 查询条件
		if (query.system) searchCondition.system = query.system;
		if (query.status) searchCondition.status = query.status;
		if (query.orderNumber) searchCondition.orderNumber = { $regex: query.orderNumber, $options: 'i' };
		if (query.remark) searchCondition.remark = { $regex: query.remark, $options: 'i' };

		// 时间范围查询
		if (query.startTime && query.endTime) {
			searchCondition.createTime = {
				$gte: new Date(query.startTime),
				$lte: new Date(query.endTime),
			};
		}

		const page = parseInt(query.page) || 1;
		const limit = parseInt(query.limit) || 10;
		const skip = (page - 1) * limit;

		const total = await orderMod.countDocuments(searchCondition);
		const orders = await orderMod.find(searchCondition).populate('createUser', 'userName').sort({ createTime: -1 }).skip(skip).limit(limit);

		res.json({
			code: 0,
			msg: '',
			count: total,
			data: orders,
		});
	} catch (error) {
		debug('获取订单列表错误:', error);
		res.json({ code: -1, msg: '获取订单列表失败' });
	}
});

// 新增订单
router.post('/add', async function (req, res) {
	const { userName, userId } = req.session;
	if (!userName || !userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}

	try {
		const { system, type, totalPoints, orderCount, remark, externalId } = req.body;

		// 验证必填字段
		if (!type || !totalPoints || !orderCount || orderCount <= 0) {
			return res.json({ code: -1, msg: '请填写完整的订单信息' });
		}

		// 检查用户是否存在
		const user = await userMod.findById(userId);
		if (!user) {
			return res.json({ code: -1, msg: '用户不存在' });
		}

		// 计算单个订单消耗的余额：积分数量 / 用户积分比例（结果为元，需转换为分）
		const balanceCostPerOrder = Math.round((totalPoints / user.pointsRatio) * 100);
		const totalBalanceCost = balanceCostPerOrder * orderCount;

		// 检查用户余额是否足够
		if (user.balance < totalBalanceCost) {
			return res.json({
				code: -1,
				msg: `余额不足！需要 ${(totalBalanceCost / 100).toFixed(2)} 元，当前余额 ${(user.balance / 100).toFixed(2)} 元`,
			});
		}

		// 扣除用户余额
		const balanceBefore = user.balance;
		const balanceAfter = balanceBefore - totalBalanceCost;
		await userMod.findByIdAndUpdate(userId, { balance: balanceAfter });

		// 生成批次ID
		const batchId = orderMod.generateBatchId();
		const createdOrders = [];

		// 批量创建订单
		for (let i = 0; i < orderCount; i++) {
			const orderNumber = orderMod.generateOrderNumber();

			const orderData = {
				orderNumber,
				system: system || '安卓',
				type,
				totalPoints,
				balanceCost: balanceCostPerOrder, // 记录单个订单的余额消耗（分）
				batchId,
				remark: remark || '',
				createUser: userId,
				createUserName: userName,
				createTime: new Date(),
			};

			// 只有当externalId不为空时才添加该字段
			if (externalId && externalId.trim() !== '') {
				orderData.externalId = externalId.trim();
			}

			const newOrder = new orderMod(orderData);

			await newOrder.save();
			createdOrders.push(newOrder);
		}

		// 记录余额变动
		const transactionId = balanceRecordMod.generateTransactionId();
		const balanceRecord = new balanceRecordMod({
			transactionId,
			orderNumber: batchId, // 使用批次ID作为订单号
			userId: userId,
			userName: userName,
			amount: -totalBalanceCost,
			transactionType: '订单扣款',
			balanceBefore,
			balanceAfter,
			operator: userName,
			remark: `创建${orderCount}个订单，每个订单${totalPoints}积分，消耗余额${(totalBalanceCost / 100).toFixed(2)}元`,
		});

		await balanceRecord.save();

		res.json({
			code: 0,
			msg: `成功创建${orderCount}个订单，每个订单${totalPoints}积分，消耗余额${(totalBalanceCost / 100).toFixed(2)}元`,
			data: {
				batchId,
				orderCount,
				totalBalanceCost: (totalBalanceCost / 100).toFixed(2),
				balanceCostPerOrder: (balanceCostPerOrder / 100).toFixed(2),
				remainingBalance: (balanceAfter / 100).toFixed(2),
				orders: createdOrders,
			},
		});
	} catch (error) {
		debug('创建订单错误:', error);
		res.json({ code: -1, msg: '创建订单失败: ' + error.message });
	}
});

// 修改订单备注
router.post('/remark', async function (req, res) {
	const { userName, userId } = req.session;
	if (!userName || !userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}

	try {
		const { orderId, remark } = req.body;

		let searchCondition = { _id: orderId };
		// 非管理员只能修改自己的订单
		if (userName !== adminName) {
			searchCondition.createUser = userId;
		}

		await orderMod.findOneAndUpdate(searchCondition, { remark });
		res.json({ code: 0, msg: '备注修改成功' });
	} catch (error) {
		debug('修改订单备注错误:', error);
		res.json({ code: -1, msg: '修改备注失败' });
	}
});

// 创建订单
router.post('/create', async function (req, res) {
	const { userName, userId } = req.session;
	if (!userName || !userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}

	try {
		const { system, type, targetUrl, totalPoints, amount, remark } = req.body;

		if (!system || !type || !targetUrl) {
			return res.json({ code: -1, msg: '参数不完整' });
		}

		// 生成订单号
		const orderNumber = 'ORD' + Date.now() + Math.floor(Math.random() * 1000);

		const order = new orderMod({
			orderNumber,
			system,
			type,
			targetUrl,
			totalPoints: totalPoints || 0,
			amount: amount || 0,
			status: '待处理',
			remark: remark || '',
			createTime: new Date(),
			createUser: userId,
		});

		await order.save();
		res.json({ code: 0, msg: '创建成功', data: order });
	} catch (error) {
		debug('创建订单错误:', error);
		res.json({ code: -1, msg: '创建失败' });
	}
});

// 获取订单剩余未交付积分数量
router.get('/remaining-points/:orderNumber', async function (req, res) {
	try {
		const { orderNumber } = req.params;

		let searchCondition = { orderNumber, isDeleted: false };

		const order = await orderMod.findOne(searchCondition);
		if (!order) {
			return res.json({ code: -1, msg: '订单不存在' });
		}

		const remainingPoints = order.totalPoints - order.completedPoints;

		res.json({
			code: 0,
			msg: '获取成功',
			data: {
				orderNumber: order.orderNumber,
				totalPoints: order.totalPoints,
				completedPoints: order.completedPoints,
				remainingPoints: remainingPoints,
				status: order.status,
			},
		});
	} catch (error) {
		debug('获取剩余积分错误:', error);
		res.json({ code: -1, msg: '获取剩余积分失败' });
	}
});

// 上传完成的积分数量
router.post('/complete-points', async function (req, res) {
	try {
		const { orderNumber, completedPoints: rawCompletedPoints } = req.body;

		if (!orderNumber || rawCompletedPoints === undefined) {
			return res.json({ code: -1, msg: '订单编号和完成积分数量不能为空' });
		}

		// 转换为数字类型
		const completedPoints = Number(rawCompletedPoints);

		if (isNaN(completedPoints) || completedPoints < 0) {
			return res.json({ code: -1, msg: '完成积分数量必须为非负数' });
		}

		let searchCondition = { orderNumber, isDeleted: false };

		const order = await orderMod.findOne(searchCondition);
		if (!order) {
			return res.json({ code: -1, msg: '订单不存在' });
		}

		// 累积完成积分
		let newCompletedPoints = order.completedPoints + completedPoints;

		// 如果累积超出总积分，则只记录到满额
		if (newCompletedPoints > order.totalPoints) {
			newCompletedPoints = order.totalPoints;
		}

		// 更新完成积分
		const updateData = { completedPoints: newCompletedPoints };

		// 如果完成积分等于总积分，自动更新状态为已完成
		if (newCompletedPoints === order.totalPoints) {
			updateData.status = '已完成';
			updateData.completeTime = new Date();
		} else if (newCompletedPoints > 0 && order.status === '待扫码') {
			// 如果有完成积分且状态是待扫码，更新为进行中
			updateData.status = '进行中';
		}

		await orderMod.findOneAndUpdate(searchCondition, updateData);

		const remainingPoints = order.totalPoints - newCompletedPoints;

		res.json({
			code: 0,
			msg: '积分更新成功',
			data: {
				orderNumber: order.orderNumber,
				totalPoints: order.totalPoints,
				completedPoints: newCompletedPoints,
				remainingPoints: remainingPoints,
				status: updateData.status || order.status,
			},
		});
	} catch (error) {
		debug('更新完成积分错误:', error);
		res.json({ code: -1, msg: '更新完成积分失败' });
	}
});

// 上传订单截图
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 使用内存存储，先读取文件内容再处理
const upload = multer({ 
	storage: multer.memoryStorage(),
	limits: {
		fileSize: 10 * 1024 * 1024 // 10MB
	},
	fileFilter: function (req, file, cb) {
		const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp'];
		if (!allowedTypes.includes(file.mimetype)) {
			return cb(new Error('只支持图片格式 (jpeg, jpg, png, gif, bmp)'), false);
		}
		cb(null, true);
	}
});

router.post('/upload-screenshot/:orderNumber', upload.single('file'), async function (req, res) {
	try {
		const { orderNumber } = req.params;
		const { description = '' } = req.body;

		if (!orderNumber) {
			return res.json({ code: -1, msg: '订单编号不能为空' });
		}

		// 检查是否有文件上传
		if (!req.file) {
			return res.json({ code: -1, msg: '请上传文件' });
		}

		const file = req.file;

		// 查找订单
		const order = await orderMod.findOne({ orderNumber, isDeleted: false });
		if (!order) {
			return res.json({ code: -1, msg: '订单不存在' });
		}
		console.log(`更新微信截图请求，订单号: ${order}`);
		if(order.status == '待扫码'){
			return res.json({ code: -1, msg: '订单状态为待扫码，不可上传截图' });
		}

		try {
			// 生成文件名：订单号 + 描述（如果描述为空则使用时间戳）
			const safeDescription = description ? description.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '_') : new Date().getTime().toString();
			const fileName = `${orderNumber}_${safeDescription}`;

			// 查找是否已存在相同描述的截图
			const existingScreenshotIndex = order.screenshots ? 
				order.screenshots.findIndex(screenshot => screenshot.description === description) : -1;

			// 文件保存路径
			const uploadDir = path.join(__dirname, '../public/uploads/screenshots');
			if (!fs.existsSync(uploadDir)) {
				fs.mkdirSync(uploadDir, { recursive: true });
			}
			
			const ext = path.extname(file.originalname) || '.' + file.mimetype.split('/')[1];
			const filePath = path.join(uploadDir, fileName + ext);
			const relativePath = `/uploads/screenshots/${fileName}${ext}`;

			// 创建截图对象 - base64字段存储文件名
			const screenshot = {
				fileName: fileName,
				base64: fileName,  // base64字段存储文件名
				filePath: relativePath,
				uploadTime: new Date(),
				description: description,
				format: file.mimetype.split('/')[1],
				size: file.size
			};

			let updatedOrder;
			if (existingScreenshotIndex >= 0) {
				// 如果已存在相同描述的截图，则替换（删除旧文件）
				const oldScreenshot = order.screenshots[existingScreenshotIndex];
				if (oldScreenshot.filePath) {
					const oldFilePath = path.join(__dirname, '../public', oldScreenshot.filePath);
					if (fs.existsSync(oldFilePath)) {
						fs.unlinkSync(oldFilePath);
					}
				}
				
				// 保存新文件
				fs.writeFileSync(filePath, file.buffer);
				
				updatedOrder = await orderMod.findOneAndUpdate(
					{ orderNumber, isDeleted: false },
					{ $set: { [`screenshots.${existingScreenshotIndex}`]: screenshot } },
					{ new: true }
				);
			} else {
				// 如果不存在，则添加新截图
				// 保存文件
				fs.writeFileSync(filePath, file.buffer);
				
				updatedOrder = await orderMod.findOneAndUpdate(
					{ orderNumber, isDeleted: false }, 
					{ $push: { screenshots: screenshot } },
					{ new: true }
				);
			}

			res.json({
				code: 1,
				msg: existingScreenshotIndex >= 0 ? '截图替换成功' : '截图上传成功',
				data: screenshot,
			});
		} catch (updateError) {
			console.error('更新订单失败:', updateError);
			res.json({ code: -1, msg: '保存截图信息失败' });
		}
	} catch (error) {
		console.error('上传截图失败:', error);
		res.json({ code: -1, msg: '服务器错误' });
	}
});

// 获取订单截图列表
router.get('/screenshots/:orderNumber', async function (req, res) {
	try {
		const { orderNumber } = req.params;
		const { type } = req.query; // 可选的截图类型筛选

		// 查找订单
		const order = await orderMod.findOne({ orderNumber, isDeleted: false }, 'screenshots');
		if (!order) {
			return res.json({ code: -1, msg: '订单不存在' });
		}

		let screenshots = order.screenshots || [];

		// 如果指定了类型，进行筛选
		if (type) {
			screenshots = screenshots.filter((screenshot) => screenshot.type === type);
		}

		res.json({
			code: 1,
			msg: '获取截图列表成功',
			data: {
				orderNumber,
				screenshots: screenshots.sort((a, b) => new Date(b.uploadTime) - new Date(a.uploadTime)), // 按上传时间倒序
			},
		});
	} catch (error) {
		console.error('获取截图列表失败:', error);
		res.json({ code: -1, msg: '服务器错误' });
	}
});

// 设备端修改订单状态接口
router.post('/device/update-status', async (req, res) => {
	try {
		const { orderNumber, status, completedPoints } = req.body;

		if (!orderNumber || !status) {
			return res.json({ success: false, message: '订单编号和状态不能为空' });
		}

		const order = await orderMod.findOne({ orderNumber });

		if (!order) {
			return res.json({ success: false, message: '订单不存在' });
		}

		const updateData = { status };

		// 如果提供了完成积分，则更新
		if (completedPoints !== undefined) {
			const newCompletedPoints = Math.min(Number(completedPoints), order.totalPoints);
			updateData.completedPoints = newCompletedPoints;

			// 根据积分完成情况自动调整状态
			if (newCompletedPoints >= order.totalPoints) {
				updateData.status = '已完成';
			}
		}

		await orderMod.updateOne({ orderNumber }, updateData);

		res.json({
			success: true,
			message: '订单状态更新成功',
			orderNumber,
			newStatus: updateData.status,
			completedPoints: updateData.completedPoints || order.completedPoints,
		});
	} catch (error) {
		console.error('设备端更新订单状态失败:', error);
		res.json({ success: false, message: '服务器错误' });
	}
});

// 取消订单接口
router.post('/cancel', async function (req, res) {
	const { userName, userId } = req.session;
	if (!userName || !userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}

	try {
		const { orderNumber } = req.body;
		if (!orderNumber) {
			return res.json({ code: -1, msg: '订单号不能为空' });
		}

		// 查找订单
		const order = await orderMod
			.findOne({
				orderNumber,
				isDeleted: false,
			})
			.populate('createUser', 'userName balance pointsRatio');

		if (!order) {
			return res.json({ code: -1, msg: '订单不存在' });
		}

		// 检查权限：非管理员只能取消自己的订单
		if (userName !== adminName && order.createUser._id.toString() !== userId) {
			return res.json({ code: -1, msg: '无权限操作此订单' });
		}

		// 检查订单状态
		if (order.status === '已完成') {
			return res.json({ code: -1, msg: '订单已完成，无法取消' });
		}
		if (order.status === '已取消') {
			return res.json({ code: -1, msg: '订单已取消' });
		}

		// 计算退款金额
		let refundAmount = 0;
		if (order.completedPoints < order.totalPoints) {
			// 计算剩余积分
			const remainingPoints = order.totalPoints - order.completedPoints;
			// 根据用户的积分换算比例计算退款金额（分）
			const pointsRatio = order.createUser.pointsRatio || 10000; // 默认1余额=10000积分
			refundAmount = Math.round((remainingPoints / pointsRatio) * 100);

			// 确保退款金额为正整数（分）
			refundAmount = Math.max(0, refundAmount);
		}

		// 更新订单状态
		await orderMod.updateOne(
			{ _id: order._id },
			{
				status: '已取消',
				cancelTime: new Date(),
				taskDeviceName: null,
				playDeviceName: null,
				deviceStatus: null,
				deviceMessage: null,
				deviceLoginTime: null,
			},
		);

		// 引入WebSocket客户端管理，通知设备停止任务
		const { clients } = require('./wsRouter');
		const mongoose = require('../db/db.js');
		const deviceShe = require('../db/deviceShe');
		const deviceMod = mongoose.model('device_' + order.createUserName, deviceShe);

		let notifiedDevices = 0;
		const deviceNames = [];

		// 收集需要通知的设备名称
		if (order.taskDeviceName) deviceNames.push(order.taskDeviceName);
		if (order.playDeviceName) deviceNames.push(order.playDeviceName);

		// 通知所有相关设备停止任务
		for (const deviceName of deviceNames) {
			const device = await deviceMod.findOne({
				deviceName: deviceName,
			});

			if (device && device.socketId) {
				const ws = clients.get(device.socketId);
				if (ws && ws.readyState === 1) {
					// WebSocket.OPEN
					// 发送取消停止任务指令
					ws.send(
						JSON.stringify({
							type: 'deviceTask',
							serverData: {
								taskName: '取消停止任务',
								timeStamp: Date.now(),
							},
						}),
					);
					notifiedDevices++;
				}
			}
		}

		// 如果有退款，更新用户余额并记录财务流水
		if (refundAmount > 0) {
			const user = await userMod.findById(order.createUser._id);
			const balanceBefore = user.balance || 0;
			const balanceAfter = balanceBefore + refundAmount;

			// 更新用户余额
			await userMod.updateOne({ _id: order.createUser._id }, { balance: balanceAfter });

			// 生成交易流水号
			const transactionId = balanceRecordMod.generateTransactionId();

			// 记录财务流水
			await balanceRecordMod.create({
				transactionId,
				orderNumber: order.orderNumber,
				userId: order.createUser._id,
				userName: order.createUser.userName,
				amount: refundAmount,
				transactionType: '后台充值',
				balanceBefore,
				balanceAfter,
				operator: userName,
				remark: `取消订单退款，剩余积分：${order.totalPoints - order.completedPoints}，退款金额：${(refundAmount / 100).toFixed(2)}元`,
			});
		}

		res.json({
			code: 1,
			msg: refundAmount > 0 ? `订单取消成功，退款金额：${(refundAmount / 100).toFixed(2)}元，已通知${notifiedDevices}个设备停止任务` : `订单取消成功，已通知${notifiedDevices}个设备停止任务`,
			data: {
				orderNumber: order.orderNumber,
				refundAmount,
				remainingPoints: order.totalPoints - order.completedPoints,
				notifiedDevices,
			},
		});
	} catch (error) {
		console.error('取消订单失败:', error);
		res.json({ code: -1, msg: '取消订单失败：' + error.message });
	}
});

// 重扫接口
router.post('/rescan', async function (req, res) {
	const { userName, userId } = req.session;
	if (!userName || !userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}

	try {
		const { orderNumber } = req.body;

		if (!orderNumber) {
			return res.json({ code: -1, msg: '订单号不能为空' });
		}

		// 查找订单
		const order = await orderMod
			.findOne({
				orderNumber,
				isDeleted: false,
			})
			.populate('createUser', 'userName');

		if (!order) {
			return res.json({ code: -1, msg: '订单不存在' });
		}

		// 检查权限：非管理员只能操作自己的订单
		if (userName !== adminName && order.createUser._id.toString() !== userId) {
			return res.json({ code: -1, msg: '无权限操作此订单' });
		}

		// 检查订单状态是否允许重扫
		const allowedStatuses = ['登陆失效', '安全验证', '进行中', '待处理'];
		if (!allowedStatuses.includes(order.status)) {
			return res.json({ code: -1, msg: '当前订单状态不支持重扫操作' });
		}
		
		// 删除OP数据
		await orderMod.updateOne(
			{ _id: order._id },
			{
				$unset: {
					opData: 1,
					'loginInfo.qq': 1,
					'loginInfo.nickname': 1,
					'loginInfo.openid': 1,
					'loginInfo.access_token': 1,
					'loginInfo.pay_token': 1,
					'loginInfo.key': 1,
					'loginInfo.auth_time': 1,
					'loginInfo.loginTime': 1,
					'loginInfo.loginType': 1,
					'loginInfo.wechat': 1,
				},
				status: '待扫码',
				taskDeviceName:null,
				playDeviceName:null,
				wechatScreenshot:null,
				screenshotUpdateTime:null,
				deviceMessage:null,
				deviceLoginTime:null,
				deviceStatus:null,
			},
		);

		// 引入WebSocket客户端管理
		const { clients } = require('./wsRouter');
		const mongoose = require('../db/db.js');
		const deviceShe = require('../db/deviceShe');
		const deviceMod = mongoose.model('device_' + order.createUserName, deviceShe);

		let notifiedDevices = 0;
		const deviceNames = [];

		// 收集需要通知的设备名称
		if (order.taskDeviceName) deviceNames.push(order.taskDeviceName);
		if (order.playDeviceName) deviceNames.push(order.playDeviceName);

		// 通知所有相关设备
		for (const deviceName of deviceNames) {
			const device = await deviceMod.findOne({
				deviceName: deviceName,
			});

			if (device && device.socketId) {
				const ws = clients.get(device.socketId);
				if (ws && ws.readyState === 1) {
					// WebSocket.OPEN
					// 发送停止任务指令
					ws.send(
						JSON.stringify({
							type: 'deviceTask',
							serverData: {
								taskName: '重扫停止任务',
								timeStamp: Date.now(),
							},
						}),
					);
					notifiedDevices++;
				}
			}
		}

		// 返回结果
		if (notifiedDevices > 0) {
			return res.json({
				code: 1,
				msg: `重扫成功，OP数据已清除，已通知${notifiedDevices}个设备停止任务，订单状态已重置为待扫码`,
			});
		} else {
			return res.json({
				code: 1,
				msg: '重扫成功，OP数据已清除，订单状态已重置为待扫码',
			});
		}
	} catch (error) {
		console.error('重扫操作失败:', error);
		res.json({ code: -1, msg: '重扫操作失败：' + error.message });
	}
});

module.exports = router;
